package com.coderdream.chapter10.strategy.sample;

import java.util.Random;

public class ProbStrategy implements Strategy {

	private Random random;

	private int prevHandValue = 0;

	private int currentHandValue = 0;

	private int[][] history = { { 1, 1, 1, }, { 1, 1, 1, }, { 1, 1, 1, }, };

	public ProbStrategy(int seed) {
		this.random = new Random(seed);
	}

	public Hand nextHand() {
		int bet = this.random.nextInt(this.getSum(this.currentHandValue));
		int handvalue = 0;

		if (bet < this.history[currentHandValue][0]) {
			handvalue = 0;
		} else if (bet < this.history[currentHandValue][0]
				+ this.history[currentHandValue][1]) {
			handvalue = 1;
		} else {
			handvalue = 2;
		}

		this.prevHandValue = this.currentHandValue;
		this.currentHandValue = handvalue;

		return Hand.getHand(handvalue);
	}

	public void study(boolean win) {
		if (win) {
			this.history[prevHandValue][currentHandValue]++;
		} else {
			this.history[prevHandValue][(currentHandValue + 1) % 3]++;
			this.history[prevHandValue][(currentHandValue + 2) % 3]++;
		}

	}

	private int getSum(int hv) {
		int sum = 0;

		for (int i = 0; i < 3; i++) {
			sum += history[hv][i];
		}

		return sum;
	}
}
